package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        //查询当前用户的信息
        User user = userDao.findByUsername(username);
        if(user ==null){
            return null;
        }
        //根据当前用户id查询角色信息
        Set<Role> roles = roleDao.findByUserId(user.getId());
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);

            //根据角色ID查询关联的菜单
            //获取父菜单
            LinkedHashSet<Menu> menus = menuDao.findMenuByRoleId(roleId);
            //遍历父菜单 拿到父菜单的id,再拿到权限的id 查到子菜单
            for (Menu menu : menus) {
                Integer menuId = menu.getId();
                Map map = new HashMap<>();
                map.put("menuId",menuId);
                map.put("roleId",roleId);
                List<Menu> sonlist = menuDao.findsonMenuBymenuIdandroleId(map);
                menu.setChildren(sonlist);
            }
            role.setMenus(menus);
        }
        user.setRoles(roles);//将角色塞进去
        return user;
    }
}
